﻿using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using MassIntellect.Drawing;

namespace MassIntellect.Presentation
{
	public class ActiveControl : ActiveShape, IActivePointControl
	{
		public ActiveControl()
		{ }

		public static ActiveControl Create<T>()
			where T: Shape, new()
		{
			return new ActiveControl(new T());
		}

		public ActiveControl(Shape shape)
			: base(shape)
		{

		}

		List<PointF> pnts = new List<PointF>();

		#region IActivePointControl Members

		public float GetNearActivePoint(PointF pnt, out PointF crd)
		{
			float fl, dist = float.MaxValue;
			crd = new PointF(float.NaN, float.NaN);
			foreach (var item in GetActivePoints())
				if ((fl = pnt.DistanceTo(item)) < dist)
				{
					dist = fl;
					crd.X = item.X;
					crd.Y = item.Y;
				}

			return dist;
		}

		public virtual IEnumerable<PointF> GetActivePoints()
		{
			var b = Bounds;
			var pf = new[] {
			               	Shape.Joint(new PointF(b.X, b.Y)),
			               	Shape.Joint(new PointF(b.Right - b.Width / 2, Y)),
			               	Shape.Joint(new PointF(b.Right, Y)),
			               	Shape.Joint(new PointF(b.Right, b.Y + b.Height / 2)),
			               	Shape.Joint(new PointF(b.Right, b.Bottom)),
			               	Shape.Joint(new PointF(b.X + b.Width / 2, b.Bottom)),
			               	Shape.Joint(new PointF(b.X, b.Bottom)),
			               	Shape.Joint(new PointF(b.X, b.X + b.Height / 2))};
			return
				pf.Where(s => 
				         !float.IsNaN(s.X) && !float.IsNaN(s.Y))
					.Distinct();
		}

		#endregion
	}
}